package com.vastcom.fabric.server.action;

import com.vastcom.fabric.server.service.FabricService;
import com.vastcom.fabric.server.tools.Const;
import com.vastcom.fabric.server.tools.FabricClient;
import org.hyperledger.fabric.sdk.Orderer;
import org.hyperledger.fabric.sdk.Peer;
import org.hyperledger.fabric.sdk.TransactionRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@CrossOrigin
@RestController
@PreAuthorize("hasAuthority('admin')")
@RequestMapping("/manage")
public class ManageAction {


    private Logger log= LoggerFactory.getLogger(ManageAction.class);

    @Autowired
    private FabricService fabricService;

    @PostMapping("invokeByJson")
    @ResponseBody
    public boolean invokeByJson(@RequestParam("key") String key, @RequestParam("value") String value) throws Exception {

        HashMap m = new HashMap();
        try {
            log.info("ManageAction-invokeByJson"+key);
            FabricClient fabricClient = new FabricClient(fabricService.getMyUserContext());
//            根据组织节点名称 获取peer节点
            Peer peer0 = fabricClient.getPeerByName(Const.PEER_RAW_MATERIA_NAME);

            List<Peer> peerList = new ArrayList<>();
            peerList.add(peer0);

//            获取组织节点
            Orderer orderer = fabricClient.getOrder();


            String initArgs[] = {"a", key, value};
            //boolean flag= fabricClient.invoke("test", TransactionRequest.Type.GO_LANG,"basicinfo",orderer,peerList,"invoke",initArgs);
            boolean flag=fabricClient.invoke("mychannel", TransactionRequest.Type.GO_LANG,"zzytest",orderer,peerList,"set",initArgs);

//            boolean flag = fabricClient.invoke("sigma", TransactionRequest.Type.GO_LANG, "test", orderer, peerList, "setjsondata", initArgs);
            if (flag) {
                return true;
            } else {
                return false;

            }


        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }


}
